package com.byx.chatclient;

import android.app.Activity;
import android.app.Application;
import android.content.ContentProvider;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.byx.chatclient.entity.UserPo;
import com.byx.chatclient.factory.RetrofitFactory;
import com.byx.chatclient.utils.OkHttpUtils;
import com.facebook.drawee.backends.pipeline.Fresco;

import java.util.concurrent.ConcurrentHashMap;

import cn.bingoogolapple.swipebacklayout.BGASwipeBackHelper;

/**
 * ChatApp
 *
 * @author Superb
 * @date 2021/3/15 14:42
 */
public class ChatApp extends Application {
    private static final String TAG = ChatApp.class.getSimpleName();
    private static ChatApp instance;

    private final ConcurrentHashMap<String,Object> map = new ConcurrentHashMap<>();
    private static final String LOGIN_USER_KEY = "CURRENT_LOGIN_USER";

    public static final String FILE_NAME = "chat_list.json";
    public static String CHAT_LIST_FILE;
    public static String BASE_FILE_DIR;
    public static String AVATAR_DIR;
    public static String IMAGE_DIR;
    public static String AUDIO_DIR;
    public static String VIDEO_DIR;
    public static String FILES_DIR;

    private int mActivityCount = 0;
    /**
     * Called when the application is starting, before any activity, service,
     * or receiver objects (excluding content providers) have been created.
     *
     * <p>Implementations should be as quick as possible (for example using
     * lazy initialization of state) since the time spent in this function
     * directly impacts the performance of starting the first activity,
     * service, or receiver in a process.</p>
     *
     * <p>If you override this method, be sure to call {@code super.onCreate()}.</p>
     *
     * <p class="note">Be aware that direct boot may also affect callback order on
     * Android {@link Build.VERSION_CODES#N} and later devices.
     * Until the user unlocks the device, only direct boot aware components are
     * allowed to run. You should consider that all direct boot unaware
     * components, including such {@link ContentProvider}, are
     * disabled until user unlock happens, especially when component callback
     * order matters.</p>
     */
    @Override
    public void onCreate() {

        super.onCreate();
        /**
         * 初始化okHttpClient
         */
        OkHttpUtils.init();
        /**
         * 初始化retrofit
         */
        RetrofitFactory.init();
        Fresco.initialize(this);
        /*
         * 必须在 Application 的 onCreate 方法中执行 BGASwipeBackHelper.init 来初始化滑动返回
         * 第一个参数：应用程序上下文
         * 第二个参数：如果发现滑动返回后立即触摸界面时应用崩溃，请把该界面里比较特殊的 View 的 class 添加到该集合中，目前在库中已经添加了 WebView 和 SurfaceView
         */
        BGASwipeBackHelper.init(this, null);
        instance = this;

        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) {
                Log.d(TAG, "onActivityCreated");
            }

            @Override
            public void onActivityStarted(@NonNull Activity activity) {
                Log.d(TAG, "onActivityStarted");
                mActivityCount++;
            }

            @Override
            public void onActivityResumed(@NonNull Activity activity) {
                Log.d(TAG, "onActivityResumed");
            }

            @Override
            public void onActivityPaused(@NonNull Activity activity) {
                Log.d(TAG, "onActivityPaused");
            }

            @Override
            public void onActivityStopped(@NonNull Activity activity) {
                Log.d(TAG, "onActivityStopped");
                mActivityCount--;
            }

            @Override
            public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {
                Log.d(TAG, "onActivitySaveInstanceState");
            }

            @Override
            public void onActivityDestroyed(@NonNull Activity activity) {
                Log.d(TAG, "onActivityDestroyed");
            }
        });

        BASE_FILE_DIR = getExternalFilesDir(null).getAbsolutePath();
        AVATAR_DIR = BASE_FILE_DIR + "/avatar";
        IMAGE_DIR = getExternalFilesDir(Environment.DIRECTORY_PICTURES).getAbsolutePath();
        AUDIO_DIR = BASE_FILE_DIR + "/audio";
        VIDEO_DIR = BASE_FILE_DIR + "/video";
        FILES_DIR = BASE_FILE_DIR + "/files";
    }

    public void save(String key,Object value){
        map.put(key,value);
    }

    public void saveCurrentUser(UserPo userPo){
        map.put(LOGIN_USER_KEY,userPo);
    }

    public UserPo getUserPo(){
        return (UserPo) map.get(LOGIN_USER_KEY);
    }

    public void clear(){
        map.clear();
    }

    public static ChatApp getInstance(){
        if (instance == null){
            throw new IllegalStateException("app not init...");
        }
        return instance;
    }

    public int getActivityCount() {
        return mActivityCount;
    }

    public boolean isRunningInBackground(){
        return this.mActivityCount == 0;
    }

    public static String toSdvPath(String localPath){
        return "file://" + localPath;
    }
}
